package com.augurit.gzcgwsp.exchangeOtherData.web;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springside.modules.utils.SpringContextHolder;

import com.augurit.common.base.form.ResultForm;
import com.augurit.common.syslog.service.ISysLoginLogService;
import com.augurit.common.syslog.tool.SysTraceLogWriter;
import com.augurit.common.syslog.web.form.SysLoginLogForm;
import com.augurit.common.system.service.auth.ILoginUserService;
import com.augurit.common.system.service.org.IAcMenuService;
import com.augurit.common.system.service.org.IAcRoleService;
import com.augurit.common.system.util.MsgUtils;
import com.augurit.common.system.util.OrgUtils;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.system.web.org.form.OmOrgForm;
import com.augurit.gzcgwsp.commonex.system.service.org.IOmOrgServiceEX;
import com.augurit.gzcgwsp.readAndParseXML.ReadAndParseXMLDemo;
import com.kingyea.sso.authorized.SsoAuthorized;

/**
 * 内门户获取用户的操作
 * @author Administrator
 *
 */


public class SSOAuth extends SsoAuthorized   {
	private static ApplicationContext ctx = SpringContextHolder.getApplicationContext();
	private static final Logger logger = Logger.getLogger(SSOAuth.class);
	@Override
	public void authorized(HttpServletRequest request, HttpServletResponse response,
			String username) {
		ILoginUserService loginService=(ILoginUserService) ctx.getBean("loginUserServiceImpl");			
			LoginUserForm loginUser=loginService.getLoginUserInfo(username);	
			System.out.println("username ======================================================= "+username);
			logger.error("username = "+username);
			// 加载当前登录用户所拥有的功能ID集合
			boolean hasFuncs = initLoginUserFuncs(loginUser,request);
			if(!hasFuncs){
				try {
					response.sendRedirect(request.getContextPath() + "/auth/login.action");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if(loginUser!=null){
	            // 加载用户部门信息
	            initLoginUserOrg(loginUser);
				
				// 加载当前登录用户所拥有的角色ID集合
				initLoginUserRoles(loginUser);
				
				// 加载当前登录用户所拥有的菜单ID集合
				initLoginUserMenus(loginUser);
				
				//记录用户登录信息
				recordLoginInfo(request,response,loginUser.getUser().getUserName(),
						loginUser.getUser().getLoginName(), true, "内门户网站登录");

				request.getSession().setAttribute(WebContextUtils.SES_LOGIN_USER, loginUser);
			
			}else{
				try {
					response.sendRedirect(request.getContextPath() + "/auth/login.action");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	}
	
	
	/**
     * 加载当前登录用户所拥有的角色ID集合
     * @param loginUser
     */
    private void initLoginUserOrg(LoginUserForm loginUser){
    	
    	try {
			IOmOrgServiceEX IOmOrgServiceEX=(IOmOrgServiceEX) ctx.getBean("omOrgServiceImplEX");
			OmOrgForm orgForm = IOmOrgServiceEX.getTopParentOrgOfUser(loginUser.getUser().getUserId());
			loginUser.setOrg(orgForm);
		} catch (BeansException e) {
			logger.error("单点登录3"+SysTraceLogWriter.MESSAGE_SEPARATOR + e.getMessage(), e);
		}
    }

	/**
	 * 加载当前登录用户所拥有的角色ID集合
	 * @param loginUser
	 */
	private void initLoginUserRoles(LoginUserForm loginUser){
		IAcRoleService acRoleService=(IAcRoleService) ctx.getBean("acRoleServiceImpl");
		Long[] roleIds = acRoleService.getAllRoleIdsByUserId(loginUser.getUser().getUserId());
		loginUser.setRoleIds(roleIds);
	}
	/**
	 * 加载当前登录用户所拥有的菜单ID集合
	 * @param loginUser
	 */
	private void initLoginUserMenus(LoginUserForm loginUser){
		IAcMenuService acMenuService=(IAcMenuService) ctx.getBean("acMenuServiceImpl");
		Long[] menuIds = acMenuService.getAllRelatedMenuIds(loginUser.getFuncIds());
		loginUser.setMenuIds(menuIds);
	}
	
	
	
	/**
	 * 记录用户的登录信息
	 * @param userName 用户名，如果用户没有输入，用户名为anonymous
	 * @param success true,登录成功，反之则相反
	 * @param msg 登录信息
	 */
	private void recordLoginInfo(HttpServletRequest request,HttpServletResponse response,
			String userName,String loginName, boolean success,String msg){
		SysLoginLogForm form = new SysLoginLogForm();
		form.setClientIp(request.getRemoteAddr());
		form.setLoginTime(new Date());
		form.setUserName(userName);
		form.setLoginState(success?"Y":"N");
		form.setLoginMessage(msg);
		try {
			ISysLoginLogService sysLoginLogService=(ISysLoginLogService) ctx.getBean("sysLoginLogServiceImpl");
			sysLoginLogService.save(form);
			Cookie c = new Cookie("loginName",loginName);//cookie记录用户名称
			c.setPath("/");   
			c.setMaxAge(3600000);
			response.addCookie(c);
		} catch (Exception e) {
			
		}		
	}
	
	/**
	 * 加载当前登录用户所拥有的功能ID集合
	 * @param loginUser
	 * @return false表示用户不能访问任何功能，true表示用户存在可访问的功能
	 */
	private boolean initLoginUserFuncs(LoginUserForm loginUser,HttpServletRequest request){
		IAcRoleService acRoleService=(IAcRoleService) ctx.getBean("acRoleServiceImpl");
		Long[] funcIds = acRoleService.getFuncIdsByUserId(loginUser.getUser().getUserId());
		
		if(funcIds != null && funcIds.length > 0){
			loginUser.setFuncIds(funcIds);
			request.getSession().setAttribute(WebContextUtils.SES_LOGIN_USER_FUNC, OrgUtils.convertToString(funcIds, ","));
			return true;
		}else
			return false;
	}
}
